﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web;
using System.Web.Caching;

namespace JCFrameWork.Web.Cacheing
{
    public class WebCacheProvider : CacheProviderBase
    {
        public WebCacheProvider() : this(null) { }

        public WebCacheProvider(ICacheProvider innerCache)
        {
            this.m_innerCache = innerCache;
            this.MaxTimeStampDataExpire = new TimeSpan(0, 15, 0);
            this.m_cache = HttpRuntime.Cache;
        }

        public TimeSpan MaxTimeStampDataExpire { get; set; }

        private ICacheProvider m_innerCache;

        private Cache m_cache;

        public override void Set(string key, object value)
        {
            this.Set(key, value, DateTime.Now.Add(this.MaxTimeStampDataExpire));
        }

        public override void Set(string key, object value, DateTime expiration)
        {
            this.m_cache.Insert(key, value, null, expiration, Cache.NoSlidingExpiration);
        }

        public override void Remove(string key)
        {
            this.m_cache.Remove(key);
        }

        public override bool Contains(string key)
        {
            return this.m_cache.Get(key) != null;
        }

        public override int Count
        {
            get { return this.m_cache.Count; }
        }

        public override void Flush()
        {
            var enumerator = this.m_cache.GetEnumerator();
            while (enumerator.MoveNext())
            {
                this.m_cache.Remove(enumerator.Key.ToString());
            }
        }

        public override object GetData(string key)
        {
            return this.m_cache.Get(key);
        }

        public bool GetTimeStampData<T>(string timeStampKey, string cacheKey, out T data)
        {
            return this.GetData<T>(cacheKey, out data);
        }


        public void SetTimeStampData(string timeStampKey, string cacheKey, object data)
        {
            this.Set(cacheKey, data);
        }
    }
}
